package org.teamh.artificialIntelligence;

import org.teamh.gui.ingame.data_structure.SafeList.Element;
import org.teamh.logic.datamodel.Creep;

public class CreepUpdater extends Thread {

	private boolean running;

	@Override
	public synchronized void start() {
		super.start();

		running = true;
	}

	@Override
	public void run() {

		while (running) {
			
			Element<Creep> next = AIInterfaceManager.datamodelManager.getCreeps().getHead();
			Creep c;
			while (next != null) {
				c = next.getE();
				
				updateCreep(c, 30);
				
				next = next.getNext();
			}
			
			try {
				Thread.sleep(30);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void updateCreep(Creep c, float timeElapsed) {
		c.addToWalkedDistance(timeElapsed);
		
		if(c.getCurrentWaypoint() == null) {
			return;
		}
		
		float curDistance = (float)(c.getCurrentWaypoint().getWayToPoint() * c.getWalkedDistance() * c.getSpeed() / 1000);
		
		if(curDistance > c.getCurrentWaypoint().getWayToPoint()) {
			c.setWorldX(c.getCurrentWaypoint().getWorldX() + c.getVector()[0] * c.getCurrentWaypoint().getWayToPoint());
			c.setWorldZ(c.getCurrentWaypoint().getWorldY() + c.getVector()[1] * c.getCurrentWaypoint().getWayToPoint());
		} else {
			c.setWorldX(c.getCurrentWaypoint().getWorldX() + c.getVector()[0] * curDistance);
			c.setWorldZ(c.getCurrentWaypoint().getWorldY() + c.getVector()[1] * curDistance);
		}
	}
	
	public void setRunning(boolean running) {
		this.running = running;
	}
}
